<?php
/**
 * *********************************************************************************************************************
 * 申通派件通知接口(新)
 * *********************************************************************************************************************
 */

namespace soa\parter\sto;
use artisan\http;

class StoDelivery extends delivery
{
    public static $requestUrl='http://stokb.sto-express.cn:22227/couriersentlist/app/courierSentList!getCourierSentList.action';//敏思达新

    public function getDeliveryList($siteName, $empNo, $beginDate='', $endDate=''){

        $fliter = 0;//是否使用请求时间来过滤返回的结果

        $beginDate = $beginDate ? date('Y-m-d H:i:s', strtotime($beginDate)) : date('Y-m-d 00:00:00');
        $endDate = $endDate ? date('Y-m-d H:i:s', strtotime($endDate)) : date('Y-m-d 23:59:59');
        $beginTime = strtotime(date('Y-m-d 00:00:00', strtotime($beginDate)));
        $endTime = strtotime(date('Y-m-d 23:59:59', strtotime($endDate)));

        if($endTime < strtotime(date('Y-m-d 00:00:00',strtotime('-2 day')))){
            return '不支持3天前的查询！';
        }
        if($beginTime < strtotime(date('Y-m-d 00:00:00',strtotime('-2 day')))){
            $beginDate = date('Y-m-d 00:00:00',strtotime('-2 day'));
            $beginTime = strtotime(date('Y-m-d 00:00:00', strtotime($beginDate)));
        }



        //测试数据
//        $courierSentList=json_decode('[
//        {
//            "billCode": "227225069243",
//"scanTime": "2016-06-03 08:29:31",
//"latestBillState": "签收"
//},
//        {
//            "billCode": "227255827220",
//"scanTime": "2016-06-03 08:29:29",
//"latestBillState": "签收"}]',true);
        //$this->service_url='http://222.66.109.134:22226/stoPlatform/app/courierSentList!getCourierSentList.action';//设置新的请求接口(测试地址)
//        $this->service_url='http://222.66.39.203:22221/stoPlatform/app/courierSentList!getCourierSentList.action';//设置新的请求接口(正式地址)
        $this->service_url = self::$requestUrl;
        $courierSentList=parent::getDeliveryList($siteName, $empNo, $beginDate, $endDate);//新接口数据

        if(!is_array($courierSentList)){
            return $courierSentList;
        }
        //兼容原来接口返回数据格式
        $retData=[
            'billCodes'=>[],
            'billInfos'=>[]
        ];
        foreach($courierSentList as $eachBillInfo){
            if($fliter && !empty($eachBillInfo['scanTime'])){
                $time = strtotime($eachBillInfo['scanTime']);
                if($time > $endTime || $time < $beginTime){
                    continue;
                }
            }
            $retData['billCodes'][]=$eachBillInfo['billCode'];
            $retData['billInfos'][$eachBillInfo['billCode']]=$eachBillInfo;//保存 单号=>(单号,时间)信息
        }
        return $retData;
    }

    /*查询快件最近状态,返回中文状态:签收，派送...*/
    public function queryDeliveryLatestStatus($waybillNo){
        $status='未知';
        //正式地址
        $this->service_url='http://222.66.39.203:22221/stoPlatform/app/waybillState!getWaybillLatestStatus.action';//设置新的请求接口
        //测试地址
//        $this->service_url='http://222.66.109.134:22226/stoPlatform/app/waybillState!getWaybillLatestStatus.action';//设置新的请求接口
        $logistics_interface = $waybillNo;
        $data_digest = base64_encode( md5( $logistics_interface . $this->getKey()));
    $time1 = time();
        $result = http::get($this->getServiceUrl(), [
            'logistics_interface' => $logistics_interface,
            'data_digest' => $data_digest
        ], ['TIMEOUT' => 50]);
    $gapTime=time()-$time1;
        if($result){
            $result = json_decode($result, true);
            if(json_last_error() ==0 && $result['isSuccess'] && isset($result['latestBillState'])){
                $status=$result['latestBillState'];
            }elseif(isset($result['message'])){
                $status=$result['message'];
                logDebug('no:'.$waybillNo.':'.$result,'queryDeliveryLatestStatus',$gapTime);
            }else{
                logDebug('no:'.$waybillNo.':'.$result,'status_timeout',$gapTime);
            }
        }
        return $status;
    }

    /*查询快件最近状态,返回英文状态:sign，problem,unknow*/
    public function queryDeliveryLatestEnStatus($waybillNo){
        $status=$this->queryDeliveryLatestStatus($waybillNo);
        if(strstr($status,'签收')){
            $status='sign';
        }else if(strstr($status,'问题')||strstr($status,'疑难')){
            $status='problem';
        }else{
            $status='unknow';
        }
        return $status;
    }

    //获取单号每种扫描类型的信息
    public static function getExpressOperate($expressNos)
    {
        $params = [
            'appKey'    => 'newkuaibao',
            'appSecret' => '017828622b064afa9588e87d1fd53f92',
            'billCode'  => implode(',', $expressNos), // 英文逗号分隔，最多一次查20个单号
            'format'    => 'json',
            'sort'      => 'asc', // 兼容旧版 参见备份文件sto_default2
        ];
        $url = 'http://expressapi.sto-express.cn:8000/api/Track/GetScans/?' . http_build_query($params);

        $timeout=5;//超时
        $time1 = time();
        //直接返回原始数据
        $raw_data = http::get($url,array(),array('TIMEOUT'=>$timeout));
        if(empty($raw_data)){
            //logError('超时无响应', 'sto_express_operate', (time()-$time1));
            return '超时无响应';
        }
        else {
            $data = json_decode($raw_data, true);

            if(json_last_error() ==0 && $data && $data['Status'] && $data['Data']){
                return $data['Data'];
            }else{
                logDebug($data,'sto_express_operate',(time()-$time1));
                return null;
            }
        }

    }

    public static function getUrl()
    {
        return self::$requestUrl;
    }
}